﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Threading;
using wrzy.utll;
using System.Runtime.InteropServices;

namespace wrzy
{
    class fzj
    {
        [DllImport("msvcrt.dll")]
        public static extern int _getch();
        [DllImport("msvcrt.dll")]
        public static extern int _kbhit();

        [DllImport("Kernel32.dll")]
        public static extern int WaitForSingleObject(IntPtr hHandle, int dwMillisenconds);

        int iChannel;
        IntPtr hDevice;  //  device object handle
        Int32 DeviceID;    //  device ID
        Int32 Key;
        Byte[] bDISts = new Byte[16];
        Byte[] bDOSts = new Byte[16];

        public fzj()//利用构造函数进行设备的初始化
        {
            ini ini=new ini("fuel.ini");
            DeviceID = 0;
            hDevice = PCI2312.PCI2312_CreateDevice(DeviceID);	// Create Device object
            if (hDevice == (IntPtr)(-1))
            {
                Console.WriteLine("CreateDevice Error...");
                _getch();
                return;
            }
            for (iChannel = 0; iChannel < 16; iChannel++)
            {
                if (iChannel % 2 == 0)
                    bDOSts[iChannel] = 0; // 偶数通道赋为低电平"0"
                else
                    bDOSts[iChannel] = 1; // 奇数通道赋为高电平"1"
            }
        }
        
        /// <summary>
        /// 调用这个方法的作用是取得开关量信号
        /// </summary>
        /// <returns>
        /// 如果封闭机已经准备好了，返回true，否则返回false
        /// </returns>
        public int GetDeviceDI()
        {
            
            if(PCI2312.PCI2312_GetDeviceDI(hDevice,@bDISts)<=0)
            {
                Thread.Sleep(1000);
                PCI2312.PCI2312_ReleaseDevice(hDevice);
                return  0;
            }
            return bDISts[2];
        }
        
        /// <summary>
        /// 当用户不再使用封闭机时，调用这个方法来释放设备对象
        /// </summary>
        public void fzjClose()  
        {
            if (hDevice != (IntPtr)(-1))
            {
                PCI2312.PCI2312_ReleaseDevice(hDevice);      // 释放设备对象	
            }
        }
        /// <summary>
        /// 封装一次
        /// </summary>
        public void SetDeviceDO3(byte intSign)
        {
            bDOSts[0] = intSign;
            if(PCI2312.PCI2312_SetDeviceDO(hDevice,@bDOSts)<=0)
            {
                MessageBox.Show("输出错误");
                PCI2312.PCI2312_ReleaseDevice(hDevice);
            }
                               
        }
    }
}
